package com.richard.base.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import com.alibaba.android.arouter.launcher.ARouter
import com.richard.base.provider.BusProvider
import me.yokeyword.fragmentation.SupportFragment
import org.greenrobot.eventbus.EventBus

/**
 ***************************************
 * 项目名称:base
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2020/1/3     2:06 PM
 * 用途: fragment 基类
 ***************************************

 */

abstract class BaseVMFragment<VM : ViewModel>(val useBinding: Boolean = false) : SupportFragment() {

    protected lateinit var mBinding: ViewDataBinding

    lateinit var mRootView:View
    protected lateinit var mViewModel: VM

//    private val loadingLayout: LoadingLayout by lazy { LoadingLayout.wrap(wrapView()).apply {
//        setEmpty(R.layout.base_layout_empty)
//        setLoading(R.layout.base_layout_loading)
//        setRetryListener(View.OnClickListener { onRetry() })
//    } }

//    protected val mUserInfoProvider by lazy {
//        KsRouterHelper.buildUserInfoProvider() as UserInfoProvider
//    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return if (useBinding) {
            mBinding = DataBindingUtil.inflate(inflater, getLayoutResId(), container, false)
            mRootView = mBinding.root
            mRootView
        } else{
            mRootView = inflater.inflate(getLayoutResId(), container, false)
            mRootView
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mViewModel = initVm()
        initView()
        initData()
        startObserve()
        super.onViewCreated(view, savedInstanceState)
    }

    /**
     * 返回初始化 ViewModel对象
     * @return VM
     */
    abstract fun initVm(): VM

    abstract fun getLayoutResId(): Int
    abstract fun initView()
    abstract fun initData()
    abstract fun startObserve()

    open fun wrapView(): View? {
        return (activity?.findViewById<ViewGroup>(android.R.id.content))?.getChildAt(0)
    }

    override fun onDestroy() {
        super.onDestroy()
        val instance : EventBus? = BusProvider.instance
        if (instance != null && instance.isRegistered(this)) {
            BusProvider.instance?.unregister(this)
        }
    }

}